import '@umijs/max';
import { message, Select } from 'antd';
import React, { useState } from 'react';
import Paragraph from 'antd/lib/typography/Paragraph';
import Search from 'antd/lib/input/Search';
import { EditableProTable, ProColumns } from '@ant-design/pro-components';
import { invokeInterfaceInfoUsingPost } from '@/services/api/interfaceInfoController';

export type RequestParamsField = {
  id: React.Key;
  fieldName?: string;
  type?: string;
  desc?: string;
  required?: string;
  value?: string;
};

export type Props = {
  requestParams?: API.RequestParamsField[];
  interfaceInfo?: API.InterfaceInfoVO;
};

const ToolsTab: React.FC<Props> = (props) => {
  const { requestParams, interfaceInfo } = props;

  const initDataSource = () => {
    const res = [] as RequestParamsField[];
    requestParams?.forEach((item, index) => {
      res.push({ ...item, id: index, value: '' } as RequestParamsField);
    });
    return res;
  };

  const [responseData, setResponseData] = useState<any>();
  const [loading, setLoading] = useState<boolean>(false);

  const [dataSource, setDataSource] = useState<readonly RequestParamsField[]>(() =>
    initDataSource(),
  );
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() => {
    return dataSource.map((item) => item.id as React.Key);
  });

  const selectAfter = (
    <Select
      disabled
      defaultValue={interfaceInfo?.method}
      style={{ width: 120 }}
      options={[
        { value: 'GET', label: 'GET', disabled: true },
        { value: 'POST', label: 'POST', disabled: true },
        { value: 'PUT', label: 'PUT', disabled: true },
        { value: 'DELETE', label: 'DELETE', disabled: true },
      ]}
    />
  );

  const requestParam: ProColumns<RequestParamsField>[] = [
    {
      title: '参数名称',
      dataIndex: 'fieldName',
      editable: false,
      width: 180,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项是必填项',
          },
        ],
      },
    },
    {
      title: '必选',
      width: 180,
      dataIndex: 'required',
      editable: false,
      render: (_, record: any) => (record.required ? '是' : '否'),
    },
    {
      title: '参数类型',
      dataIndex: 'type',
      key: 'type',
      editable: false,
    },
    {
      title: '描述',
      dataIndex: 'desc',
      key: 'desc',
      editable: false,
    },
    {
      title: '参数值',
      width: 385,
      dataIndex: 'value',
      valueType: 'text',
    },
  ];

  /**
   * 调用接口
   */
  const onSubmit = async () => {
    setLoading(true);
    const params = {
      interfaceInfoId: interfaceInfo?.id,
      paramList: [],
    } as API.InterfaceInvokeRequest;

    try {
      // 参数校验 是否为必填项
      dataSource.forEach((item) => {
        if (item.required) {
          if (item.value === '') {
            throw new Error(`${item.fieldName} 是必填项`);
          }
        }
      });

      if (editableKeys.length) {
        editableKeys.forEach((key) => {
          let param = dataSource.find((item) => {
            return item.id === key;
          });
          params.paramList?.push(param as API.InvokeRequestField);
        });
      }

      const res = await invokeInterfaceInfoUsingPost(params);
      if (res.data) {
        setResponseData(res.data);
      }
      message.success('调用成功');
    } catch (e: any) {
      message.error(e.message);
    }

    setLoading(false);
  };

  return (
    <>
      <div style={{ display: 'flex', justifyContent: 'center', justifyItems: 'center' }}>
        <Search
          loading={loading}
          size={'large'}
          readOnly
          style={{ maxWidth: 600 }}
          value={`${interfaceInfo?.host}${interfaceInfo?.url}`}
          addonBefore={selectAfter}
          enterButton="发起请求"
          onSearch={onSubmit}
        />
      </div>
      <p className="highlightLine" style={{ marginTop: 15 }}>
        请求参数设置：
      </p>
      <EditableProTable<any>
        columns={requestParam}
        rowKey="id"
        scroll={{
          x: 960,
        }}
        recordCreatorProps={false}
        value={dataSource}
        onChange={setDataSource}
        editable={{
          type: 'multiple',
          editableKeys,
          actionRender: (row, config, defaultDoms) => {
            return [defaultDoms.delete];
          },
          onValuesChange: (record, recordList) => {
            setDataSource(recordList);
          },
          onChange: setEditableRowKeys,
        }}
      />

      <p className="highlightLine" style={{ marginTop: 15 }}>
        返回结果：
      </p>
      <Paragraph copyable code style={{ fontSize: 16 }}>
        {JSON.stringify(responseData)}
      </Paragraph>
    </>
  );
};
export default ToolsTab;
